package com.imooc.spring.jdbc.dao;

import com.imooc.spring.jdbc.entity.Employee;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

public class EmployeeDao {
    private JdbcTemplate jdbcTemplate;

    public Employee findById(Integer eno) {
        String sql = "select * from employee where eno = ?";
        //将sql转为数据对象，BeanPropertyRowMapper 将数据记录转为实体对象
        //   查询单条数据
        Employee employee = jdbcTemplate.queryForObject(sql, new Object[]{eno}, new BeanPropertyRowMapper<Employee>(Employee.class));
        return employee;
    }


    public List<Employee> findByDname(String dname) {
        String sql = "select * from employee where dname = ?";
        // 查询多条
        List<Employee> list = jdbcTemplate.query(sql, new Object[]{dname}, new BeanPropertyRowMapper<>(Employee.class));
        return list;
    }

    public List<Map<String, Object>> findMapByname(String dname) {
        String sql = "select eno as empno , salary as s from employee where dname = ?";
        // 将查询结果作为Map进行封装。结果：[{empno=1, s=273.74}, {empno=2, s=835.83}]
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, new Object[]{dname});
        return maps;
    }

    public void insertEmployee(Employee employee) {
        String sql = "insert into employee(eno,ename,salary,dname,hiredate) values(?,?,?,?,?)";
        jdbcTemplate.update(sql, new Object[]{
                employee.getEno(), employee.getEname(), employee.getSalary(), employee.getDname(), employee.getHiredate()
        });
    }

    public int updateEmployee(Employee employee) {
        String sql = "UPDATE employee set ename = ? , salary = ?,dname = ? , hiredate = ? where eno = ?";
        int count = jdbcTemplate.update(sql, new Object[]{
                employee.getEname(), employee.getSalary(), employee.getDname(), employee.getHiredate(), employee.getEno()
        });
        return count;
    }

    public int deleteEmployee(Integer eno) {
        String sql = "delete from employee where eno = ?";
        return jdbcTemplate.update(sql, new Object[]{eno});
    }
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
